package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.dto.Result;
import com.gistone.commis.entity.User;
import com.gistone.commis.mapper.AttendanceMapper;
import com.gistone.commis.mapper.OvertimeMapper;
import com.gistone.commis.mapper.PersonMapper;
import com.gistone.commis.mapper.UserMapper;
import com.gistone.commis.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by wangfan on 2017/6/11.
 */

@RestController("apiUploadController")
@RequestMapping("api/upload")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    @Value("${app.uploadPath}")
    private String path;


    @Autowired
    private AttendanceMapper attendanceMapper;

    @Autowired
    private OvertimeMapper overtimeMapper;


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PersonMapper personMapper;


    /**
     * 上传党务经费相关文档
     * @param multipartFile
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "uploadConstructionFile", produces = "application/json", method = RequestMethod.POST)
    public Result uploadConstructionFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession httpSession = request.getSession();
		User user = (User) httpSession.getAttribute("userInfo");
		logger.info("用户信息：" + user.toString());
		String  community_name = user.getCommunity().getCommunityName();

		Date date =new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

		String uploadPath =path+"/construction"+"/"+community_name+"/"+year; //通过社区id保存

        File file = new File(uploadPath);
        if  (!file .exists()  && !file .isDirectory())
        {
            file .mkdirs();
        }



        if (multipartFile != null) {
            //当前上传文件的文件名称
            String fileName = multipartFile.getOriginalFilename();
            if(fileName.endsWith(".doc")||fileName.endsWith(".docx")||fileName.endsWith(".wps")){
//                String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
//                String saveFileName = "基层党组织服务群众经费使用请示-"+DateUtil.DateToStr2(date)+"."+prefix;
                File f = new File(uploadPath+"/"+fileName);
                if(f.exists()){
                    return  new Result(Status.FILE_EXISTED,"",uploadPath+"/"+fileName);
                }
                byte[] bytes = multipartFile.getBytes();
                BufferedOutputStream ops = new BufferedOutputStream(new FileOutputStream(uploadPath+"/"+fileName));

                System.out.println("成功");
                ops.write(bytes);
                ops.close();
                return  new Result(Status.SUCCESS,"",uploadPath+"/"+fileName);

            }else{
                logger.info("必须上传word文件");
                return  new Result(Status.ERROR,"","");
            }


        }
        return  new Result(Status.SUCCESS,"","");
    }

    /**
     * 上传群众经费相关文档
     * @param multipartFile
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadPublicFundFile", produces = "application/json", method = RequestMethod.POST)
    public Result uploadPublicFundFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        String  community_name = user.getCommunity().getCommunityName();

        Date date =new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

        String uploadPath =path+"/publicFund"+"/"+community_name+"/"+year; //通过社区id保存

        File file = new File(uploadPath);
        if  (!file .exists()  && !file .isDirectory())
        {
            file .mkdirs();
        }



        if (multipartFile != null) {
            //当前上传文件的文件名称
            String fileName = multipartFile.getOriginalFilename();
            if(fileName.endsWith(".doc")||fileName.endsWith(".docx")||fileName.endsWith(".wps")){
//                String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
//                String saveFileName = "基层党组织服务群众经费使用请示-"+DateUtil.DateToStr2(date)+"."+prefix;
                File f = new File(uploadPath+"/"+fileName);
                if(f.exists()){
                    return  new Result(Status.FILE_EXISTED,"",uploadPath+"/"+fileName);
                }
                byte[] bytes = multipartFile.getBytes();
                BufferedOutputStream ops = new BufferedOutputStream(new FileOutputStream(uploadPath+"/"+fileName));

                System.out.println("成功");
                ops.write(bytes);
                ops.close();
                return  new Result(Status.SUCCESS,"",uploadPath+"/"+fileName);

            }else{
                logger.info("必须上传word文件");
                return  new Result(Status.ERROR,"","");
            }


        }
        return  new Result(Status.SUCCESS,"","");
    }

    /**
     * 上传加班文档 path/加班/年/月/社区名-年-月
     * @param multipartFile
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadOvertimeFile", produces = "application/json", method = RequestMethod.POST)
    public Result uploadOvertimeFile(@RequestParam("overtimeFile") MultipartFile multipartFile,@RequestParam Integer repeat, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        String  community_name = user.getCommunity().getCommunityName();

        Date date =new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

        String uploadPath =path+"/加班/"+year+"/"+month+"/"; //勤/年/月/

        File file = new File(uploadPath);
        if  (!file .exists()  && !file .isDirectory())
        {
            file .mkdirs();
        }



        if (multipartFile != null) {
            //当前上传文件的文件名称
            String fileName = multipartFile.getOriginalFilename();
            if(fileName.endsWith(".xls")||fileName.endsWith(".xlsx")){
                String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
                String saveFileName = community_name+"-加班-"+year+"-"+month+"."+prefix;
                File f = new File(uploadPath+"/"+saveFileName);
                if(f.exists()&&repeat!=1){
                    return  new Result(Status.FILE_EXISTED,"","");
                }
                byte[] bytes = multipartFile.getBytes();
                BufferedOutputStream ops = new BufferedOutputStream(new FileOutputStream(uploadPath+"/"+saveFileName));
                ops.write(bytes);
                ops.close();

            }else{
                logger.info("必须上传Excel文件");
                return  new Result(Status.ERROR,"","");
            }


        }
        return  new Result(Status.SUCCESS,"","");
    }

    /**
     * 上传考勤文档
     * @param multipartFile
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "uploadAttFile", produces = "application/json", method = RequestMethod.POST)
    public Result uploadAttFile(@RequestParam("attFile") MultipartFile multipartFile,@RequestParam Integer repeat, HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        String  community_name = user.getCommunity().getCommunityName();

        Date date =new Date();
        Calendar now = Calendar.getInstance();
        int year =now.get(Calendar.YEAR);
        int month =now.get(Calendar.MONTH) + 1;

        String uploadPath =path+"/考勤/"+year+"/"+month+"/"; //勤/年/月/

        File file = new File(uploadPath);
        if  (!file .exists()  && !file .isDirectory())
        {
            file .mkdirs();
        }



        if (multipartFile != null) {
            //当前上传文件的文件名称
            String fileName = multipartFile.getOriginalFilename();
            if(fileName.endsWith(".xls")||fileName.endsWith(".xlsx")){
                String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
                String saveFileName = community_name+"-考勤-"+year+"-"+month+"."+prefix;
                File f = new File(uploadPath+"/"+saveFileName);
                if(f.exists()&&repeat!=1){
                    return  new Result(Status.FILE_EXISTED,"","");
                }
                byte[] bytes = multipartFile.getBytes();
                BufferedOutputStream ops = new BufferedOutputStream(new FileOutputStream(uploadPath+"/"+saveFileName));
                ops.write(bytes);
                ops.close();

            }else{
                logger.info("必须上传Excel文件");
                return  new Result(Status.ERROR,"","");
            }


        }
        return  new Result(Status.SUCCESS,"","");
    }


}
